/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.mozilla.org/MPL/MPL-1.1.html
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Authors:
 *   Danny Wilson (deCube.net - design and development)
 *     API review / implementation
 * 
 *   Martin Heidegger
 *     API review
 * 
 * All rights reserved.
 */
package hxbase.event;
 import hxbase.event.Event;

/**
	Every AutoEventGroup that is instantiated, will have it's event dispatchers automatically instantiated
	using the haxe.rtti.Infos. So all you have to do to create your own Event group, is extend.
	
	For example:
	
	class MyMouseEvents extends EventGroup {
		var thisIsnotAnEvent : Bool;
		var move : Event<{ x : Int, y : Int } -> MyComponent -> Void>;
	}
	
	var x = new MyMouseEvents();
	trace(x.move); // Event
	trace(x.thisIsnotAnEvent); // null
**/
class AutoEventGroup extends BasicEventGroup, implements haxe.rtti.Infos
{
	public function new() {
		rtti();
		super();
	}
	
	/**	This method initializes all event dispatchers using haxe.rtti **/
	private function rtti()
	{
		var cl = Type.getClass(this),
			rf = Reflect.field,
			sf = Reflect.setField,
			af : Array<String> = untyped cl.fields;
		
		if( af == null )
		{
			af = untyped cl.fields = new Array();
			var f:Xml, xml = Xml.parse(untyped cl.__rtti);
			for(x in xml.firstElement().elements())
				if( (f = x.firstElement()) != null && f.nodeName == 'c' && f.get('path') == 'hxbase.event.Event') {
					af.push(x.nodeName);
					if( rf(this, x.nodeName) == null )
						sf(this, x.nodeName, new Event());
				}
		}
		else for(f in af)
			if(rf(this, f) == null) sf(this, f, new Event());
	}
}